package com.s7.widget.utils;

import android.content.Context;
import android.util.DisplayMetrics;

/**
 * dp 与 px 尺寸互转
 */
public class PxUtil {

	public static final int COMPLEX_UNIT_PX = 1;
	public static final int COMPLEX_UNIT_DIP = 2;
	public static final int COMPLEX_UNIT_SP = 3;
	public static final int COMPLEX_UNIT_PT = 4;
	public static final int COMPLEX_UNIT_IN = 5;
	public static final int COMPLEX_UNIT_MM = 6;

	public static int px2dp(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static int dp2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static int px2sp(Context context, float pxValue) {
		final float fontScale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / fontScale + 0.5f);
	}

	public static int sp2px(Context context, float spValue) {
		final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (spValue * fontScale + 0.5f);
	}

	public static float applyDimension(Context context,int unit, float value) {
		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		switch (unit) {
		case COMPLEX_UNIT_PX:
			return value;
		case COMPLEX_UNIT_DIP:
			return value * metrics.density;
		case COMPLEX_UNIT_SP:
			return value * metrics.scaledDensity;
		case COMPLEX_UNIT_PT:
			return value * metrics.xdpi * (1.0f / 72);
		case COMPLEX_UNIT_IN:
			return value * metrics.xdpi;
		case COMPLEX_UNIT_MM:
			return value * metrics.xdpi * (1.0f / 25.4f);
		}
		return 0;
	}

}
